package com.dhnsoft.shortLink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhnsoft.shortLink.admin.common.convention.exception.ClientException;
import com.dhnsoft.shortLink.admin.common.enums.UserErrorCodeEnum;
import com.dhnsoft.shortLink.admin.dao.entity.UserDO;
import com.dhnsoft.shortLink.admin.dao.mapper.UserMapper;
import com.dhnsoft.shortLink.admin.dto.req.UserLoginReqDTO;
import com.dhnsoft.shortLink.admin.dto.req.UserRegisterReqDTO;
import com.dhnsoft.shortLink.admin.dto.req.UserUpateReqDTO;
import com.dhnsoft.shortLink.admin.dto.resp.UserLoginRespDTO;
import com.dhnsoft.shortLink.admin.dto.resp.UserRespDTO;
import com.dhnsoft.shortLink.admin.service.GroupService;
import com.dhnsoft.shortLink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.dhnsoft.shortLink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;

/**
 * ClassName: UserServiceImpl
 * Package: com.dhnsoft.shortLink.admin.service.impl
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/14 17:30
 * @Version 1.0
 */

/**
 * 用户接口实现层
 * */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements  UserService{

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;

    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDO::getUsername,username);
        UserDO userDO = baseMapper.selectOne(wrapper);
        if(userDO== null){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO,userRespDTO);
        return userRespDTO;
    }

    @Override
    public Boolean hasUsername(String username) {

        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(!hasUsername(requestParam.getUsername())){
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if(lock.tryLock()){
                try{
                    int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                    if(insert<1){
                        throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                    }
                }
                catch (DuplicateKeyException ex){
                    throw new ClientException(UserErrorCodeEnum.USER_EXIST);
                }
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                groupService.saveGroup(requestParam.getUsername(),"默认分组");
                return;
            }
            throw  new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);

        }
        finally {
            lock.unlock();
        }

    }

    @Override

    public void update(UserUpateReqDTO requestParam) {
        //TODO 验证当前用户名是否为登录用户
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class),queryWrapper);

    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO==null){
            throw new ClientException("用户不存在");
        }
        //判断用户是否登录
        if(stringRedisTemplate.hasKey("login_"+requestParam.getUsername())){
            throw new ClientException("用户已登录");
        }
        /**
         * Hash
         * key login_用户名
         * Value:
         *  key token
         *  value:Json字符串（用户信息）
         *
         * */

        //将UUID作为token值
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_"+requestParam.getUsername(),
                uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_"+requestParam.getUsername(),30, TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username,token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username,token)){
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }


}
